package com.lonely.system.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lonely.common.core.domain.BaseEntity;
import com.lonely.common.core.page.Condition;
import com.lonely.common.enums.CommonStatus;
import com.lonely.common.enums.DataScope;
import com.lonely.common.threadlocals.DataPermissionThreadLocal;
import com.lonely.common.utils.SecurityUtils;
import com.lonely.system.domain.dto.tag.SysTagPageQueryDto;
import com.lonely.system.domain.dto.tag.SysTagSubmitDto;
import com.lonely.system.domain.entity.SysTag;
import com.lonely.system.domain.vo.system.tag.SysTagPageQueryVo;
import com.lonely.system.domain.vo.system.tag.TagSelectVo;
import com.lonely.system.mapper.SysTagMapper;
import com.lonely.system.service.ISysTagService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author: 黄志标
 * @date: 2025/5/27 11:36
 * @description: 标签管理接口实现
 */
@Service
public class SysTagServiceImpl extends ServiceImpl<SysTagMapper, SysTag> implements ISysTagService {

    /**
     * 分页查询
     *
     * @param queryDto
     * @return
     */
    @Override
    public Page<SysTagPageQueryVo> page(SysTagPageQueryDto queryDto) {
        Page<SysTag> page = Condition.page(queryDto);
        LambdaQueryWrapper<SysTag> queryWrapper = new LambdaQueryWrapper<SysTag>().like(StrUtil.isNotBlank(queryDto.getTagName()), SysTag::getTagName, queryDto.getTagName())
                .eq(queryDto.getStatus() != null, SysTag::getStatus, queryDto.getStatus())
                .eq(SysTag::getFactoryId, SecurityUtils.getFactoryId());

        Page<SysTag> tagPage = super.page(page, queryWrapper);
        Page<SysTagPageQueryVo> resultPage = new Page<>();
        BeanUtils.copyProperties(tagPage, resultPage);

        if (CollUtil.isNotEmpty(tagPage.getRecords())) {
            resultPage.setRecords(tagPage.getRecords().stream().map(x -> {
                SysTagPageQueryVo tagPageQueryVo = new SysTagPageQueryVo();
                BeanUtils.copyProperties(x, tagPageQueryVo);
                return tagPageQueryVo;
            }).collect(Collectors.toList()));
        }
        return resultPage;
    }

    /**
     * 创建客户
     *
     * @param submitDto
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void create(SysTagSubmitDto submitDto) {
        Assert.isNull(submitDto.getId(), "参数错误(id)");
        checkTag(submitDto);

        SysTag sysTag = new SysTag();
        BeanUtils.copyProperties(submitDto, sysTag);
        sysTag.setFactoryId(SecurityUtils.getFactoryId());
        sysTag.setCreateBy(SecurityUtils.getUserId());
        sysTag.setUpdateBy(SecurityUtils.getUserId());
        super.save(sysTag);
    }

    /**
     * 编辑客户
     *
     * @param submitDto
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void edit(SysTagSubmitDto submitDto) {
        Assert.notNull(submitDto.getId(), "参数错误(id)");
        checkTag(submitDto);
        SysTag oldTag = super.getById(submitDto.getId());
        BeanUtils.copyProperties(submitDto, oldTag);
        oldTag.setUpdateBy(SecurityUtils.getUserId());
        super.updateById(oldTag);
    }

    /**
     * 启用客户
     *
     * @param id
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void enabled(Long id) {
        SysTag sysTag = super.getById(id);
        Assert.notNull(sysTag, "客户不存在");
        sysTag.setStatus(CommonStatus.ENABLE.code);
        super.updateById(sysTag);
    }

    /**
     * 禁用客户
     *
     * @param id
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void disable(Long id) {
        SysTag sysTag = super.getById(id);
        Assert.notNull(sysTag, "客户不存在");
        sysTag.setStatus(CommonStatus.DISABLE.code);
        super.updateById(sysTag);
    }

    /**
     * 获取客户下拉列表
     *
     * @return
     */
    @Override
    public List<TagSelectVo> getTagSelect() {
        DataPermissionThreadLocal.setDataPermission(DataScope.FACTORY, "factory_id");
        return super.list(new LambdaQueryWrapper<SysTag>()
                        .eq(SysTag::getFactoryId, SecurityUtils.getFactoryId())
                        .eq(SysTag::getStatus, CommonStatus.ENABLE.code))
                .stream().map(tag -> {
                    TagSelectVo select = new TagSelectVo();
                    select.setLabel(tag.getTagName());
                    select.setValue(String.valueOf(tag.getId()));
                    select.setTagColorType(tag.getTagColorType());
                    return select;
                })
                .collect(Collectors.toList());
    }

    /**
     * 根据标签id获取标签名称映射
     *
     * @param tagIds
     * @return
     */
    @Override
    public Map<Long, String> getTagNameMapByTagIds(List<Long> tagIds) {
        if (CollUtil.isEmpty(tagIds)) {
            return new HashMap<>();
        }
        return super.listByIds(tagIds).stream().collect(Collectors.toMap(BaseEntity::getId, SysTag::getTagName, (key1, key2) -> key1));
    }

    /**
     * 校验标签信息
     *
     * @param submitDto
     */
    private void checkTag(SysTagSubmitDto submitDto) {

        // 1. 校验标签名称是否重复
        int count = super.count(new LambdaQueryWrapper<SysTag>()
                .eq(SysTag::getTagName, submitDto.getTagName())
                .eq(SysTag::getFactoryId, SecurityUtils.getFactoryId())
                .ne(submitDto.getId() != null, SysTag::getId, submitDto.getId()));
        Assert.isTrue(count == 0, "该标签已存在");

        //2. 校验标签id是否正确
        if (submitDto.getId() != null) {
            SysTag sysTag = super.getById(submitDto.getId());
            Assert.notNull(sysTag, "标签不存在");
        }
    }
}
